﻿using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Common;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Security.Cryptography;

namespace DFGK_WMS.WebAPI.Controllers.PC.入库管理
{
    /// <summary>
    /// 入库管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "PC")]
    public class ReceivingOrderDetailController : BaseController
    {
        private readonly IReceivingOrderDetailService receivingOrderDetailService;
        private readonly IPutawayOrderRepository putawayOrderRepository;
        private readonly IReceivingBillRepository receivingBillRepository;
        private readonly IPickingOrderRepository pickingOrderRepository;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="environment"></param>
        /// <param name="receivingOrderDetailService"></param>
        /// <param name="putawayOrderRepository"></param>
        public ReceivingOrderDetailController(IWebHostEnvironment environment, IReceivingOrderDetailService receivingOrderDetailService, IPutawayOrderRepository putawayOrderRepository, IPickingOrderRepository pickingOrderRepository, IReceivingBillRepository receivingBillRepository) : base(environment)
        {
            this.receivingOrderDetailService = receivingOrderDetailService;
            this.putawayOrderRepository = putawayOrderRepository;
            this.pickingOrderRepository = pickingOrderRepository;
            this.receivingBillRepository = receivingBillRepository;
        }

        /// <summary>
        /// PC收货入库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BuildCreateStackingStorage(ReceivingBillOrderDto m)
        {
            if (m.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            string message = "";
            m.NowUserId = base.BaseGetNowUserId();
            m.NowUserName = base.BaseGetNowUserName();
           
          
            var pickobj = pickingOrderRepository.QueryEntityWhere(x => x.Status != 5);
            if (pickobj != null)
                return Ok(BaseResult.Result(false, "保存失败！有出库任务正在执行！", "500"));
            bool IsOK = receivingOrderDetailService.AddReceivingOrderDetail(m, out message);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "保存成功！分配的仓位为：" + message, "200"));
            }
            return Ok(BaseResult.Result(false, "保存失败！" + message, "500"));
        }

        /// <summary>
        /// 机械爪入库上报
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult FinishMachine(ReceivingBillOrderDto m)
        {
            if (m.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            string message = "";
            m.NowUserId = base.BaseGetNowUserId();
            m.NowUserName = base.BaseGetNowUserName();
            var pickobj = pickingOrderRepository.QueryEntityWhere(x => x.Status != 5);
            if (pickobj != null)
                return Ok(BaseResult.Result(false, "保存失败！有出库任务正在执行！", "500"));
            bool IsOK = receivingOrderDetailService.AddReceivingOrderDetail(m, out message);
            WcsTaskResultDtos wcsTaskResultDtos = new WcsTaskResultDtos();
            if (IsOK)
            {
                var code = putawayOrderRepository.QueryEntityWhere(x => x.Status != 5 && x.PalletBarcode == m.PalletBarcode)?.Code;               
                wcsTaskResultDtos.TaskCode = code;
                string[] parts = message.Substring(5).Split(separator: '_');
                wcsTaskResultDtos.Tunnel = Convert.ToInt32(parts[0]);
                wcsTaskResultDtos.Row = Convert.ToInt32(parts[1]);
                wcsTaskResultDtos.Bay = Convert.ToInt32(parts[2]);
                wcsTaskResultDtos.Level = Convert.ToInt32(parts[3]);
                if (wcsTaskResultDtos.Tunnel == 3)
                    wcsTaskResultDtos.Station = EmStation.S107;
                else
                    wcsTaskResultDtos.Station = EmStation.S106;

                return Ok(BaseResult.Result(wcsTaskResultDtos, "操作成功！", "200"));
            }
            return Ok(BaseResult.Result(wcsTaskResultDtos, "操作失败！"+message, "500"));
        }

        ///// <summary>
        ///// 机械爪（向机械爪发信号抓取货物组垛）
        ///// </summary>
        ///// <param name="m"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public IActionResult StartMachine(MachineDto m)
        //{
        //    if (m.Id <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "Id有误！"));
        //    }
        //    string message = "";
        //    var pickobj = pickingOrderRepository.QueryEntityWhere(x => x.Status != 5);
        //    if (pickobj != null)
        //        return Ok(BaseResult.Result(false, "保存失败！有出库任务正在执行！", "500"));
        //    bool IsOK = receivingOrderDetailService.StartMachine(m, out message);
        //    if (IsOK)
        //    {
        //        return Ok(BaseResult.Result(true, "操作成功！", "200"));
        //    }
        //    return Ok(BaseResult.Result(false, "操作失败！" + message, "500"));
        //}

        /// <summary>
        /// 机械爪手动结束任务
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult FinishMachines(MachineDto m)
        {
            if (m.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            string message = "";

            bool IsOK = receivingOrderDetailService.FinishMachine(m, out message);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "操作成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "操作失败！" + message, "500"));
        }

        /// <summary>
        /// 获取入库单列表
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="orderSn"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetReceivingOrderDetailList(DateTime? startTime = null, DateTime? endTime = null, string? orderSn = "", int status = 8, int pageIndex = 1, int pageSize = 8)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页参数有误！"));
            }
            int totalCount;
            var list = receivingOrderDetailService.GetReceivingOrderDetailList(startTime, endTime, orderSn, status, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
    }
}
